<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat, toYuan, copyToCliboard } from '@/hooks/util'
import * as fansApi from '@/api/fans'
import * as accountApi from '@/api/account'
import { message } from 'ant-design-vue'
import EditRemark from './components/EditRemark.vue'
import EditBalance from './components/EditBalance.vue'
import LdleFish from './LdleFish.vue'
import SearchDrawer from '@/components/search-drawer/Index.vue'

const searchDrawerRef = ref()

const route = useRoute()

const editRemarkRef = ref()
const EditBalanceRef = ref()

const activeKey = ref<string>('1')

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  robotId?: string
  city?: string
  nickName?: string
  remark?: string
  wxid?: string
  fansId?: string
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '头像',
    key: 'avatar',
    width: 100,
  },
  {
    title: '粉丝信息',
    key: 'nickName',
    width: 300,
  },
  {
    title: '平台信息',
    key: 'wechatId',
    width: 400,
  },
  {
    title: '微信信息',
    key: 'wxid',
    width: 400,
  },
  {
    title: '注册信息',
    key: 'createTime',
    width: 400,
    fixed: 'right',
  },
  // {
  //   title: '操作',
  //   key: 'action',
  //   width: 90,
  //   fixed: 'right',
  // },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await fansApi.getWechatFansList(searchParams.value)
    if (state === 200) {
      data.list.forEach((item: { isRemarkShow: boolean }) => {
        item.isRemarkShow = false
      })
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

// 拉取机器人列表
let okRobat = ref<string>()
import type { SelectProps } from 'ant-design-vue'
const robatList = ref<SelectProps['options']>([])
interface OptionList {
  label: string
  value: string
}
let optionList = ref<Array<OptionList>>([])
const getRobatList = async () => {
  const params = {
    currentPage: 1,
    pageSize: 100,
  }
  try {
    let { state, data, message: msg } = await accountApi.getList(params)
    if (state === 200) {
      robatList.value = data.list

      optionList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })
      if (data.list.length == 0) {
        // message.error('微信：无平台账号，请先添加平台账号')
        // activeKey.value = '2'
      } else if (data.list.length > 0) {
        selectRobat(data.list[0].id)
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectRobat = (selectValue: any) => {
  okRobat.value = selectValue as string
  searchParams.value.robotId = okRobat.value
  getList()
  getCityList(okRobat.value)
}

// 拉取城市列表
const cityList = ref<SelectProps['options']>([])
const getCityList = async (robotId: string) => {
  const params = {
    robotId,
  }
  try {
    let { state, data, message: msg } = await fansApi.getWechatFansCityList(params)
    if (state === 200) {
      cityList.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

onMounted(() => {
  getRobatList()
})

// 查询
const formRef = ref()
interface FormState {
  city?: string
  nickName?: string
  remark?: string
  wxid?: string
  fansId?: string
}
const formState = reactive<FormState>({})
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.nickName = formState.nickName || ''
    searchParams.value.remark = formState.remark || ''
    searchParams.value.wxid = formState.wxid || ''
    searchParams.value.fansId = formState.fansId || ''
    searchParams.value.city = formState.city || ''
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'nickName')
  Reflect.deleteProperty(searchParams.value, 'remark')
  Reflect.deleteProperty(searchParams.value, 'wxid')
  Reflect.deleteProperty(searchParams.value, 'fansId')
  Reflect.deleteProperty(searchParams.value, 'city')

  getList()
}

// 备注
const editRemark = async (id: string, remark: string) => {
  let params = {
    id,
    remark,
  }

  try {
    const { state, message: msg } = await fansApi.editWechatFansRemark(params)
    if (state === 200) {
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 余额
const editBalance = (record: any) => {
  EditBalanceRef.value.showModal(record)
}

// select搜索
const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}

const advancedSearch = () => {
  searchDrawerRef.value.showDrawer()
}
</script>

<template>
  <page-container :title="route.meta.title">
    <a-alert
      message="重要提醒"
      description="当前显示的为第一个账号的数据，如需加载指定账号数据请在右上角输入框进行选择微信账号/选择闲鱼账号操作！"
      type="warning"
      show-icon
      style="margin-bottom: 10px"
    />

    <a-card style="overflow-x: scroll">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="闲鱼" force-render>
          <LdleFish></LdleFish>
        </a-tab-pane>
        <a-tab-pane key="2" tab="微信">
          <div style="margin: 5px 0; text-align: right">
            <span>选择微信账号：</span>
            <a-select
              v-model:value="okRobat"
              @change="selectRobat"
              placeholder="请选择"
              style="width: 200px; text-align: left"
              show-search
              :options="optionList"
              :filter-option="filterOption"
            >
              <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </div>

          <div class="searchBox">
            <a-form ref="formRef" layout="inline" :model="formState">
              <a-form-item label="昵称" name="nickName">
                <a-input
                  v-model:value="formState.nickName"
                  placeholder="昵称"
                  style="width: 200px"
                />
              </a-form-item>

              <a-form-item label="备注" name="remark">
                <a-input v-model:value="formState.remark" placeholder="备注" style="width: 200px" />
              </a-form-item>

              <a-form-item label="粉丝ID" name="wxid">
                <a-input v-model:value="formState.fansId" placeholder="粉丝ID" />
              </a-form-item>

              <SearchDrawer ref="searchDrawerRef">
                <div>
                  <a-form-item label="昵称" name="nickName">
                    <a-input
                      v-model:value="formState.nickName"
                      placeholder="昵称"
                      style="width: 285px"
                    />
                  </a-form-item>

                  <a-form-item label="备注" name="remark">
                    <a-input
                      v-model:value="formState.remark"
                      placeholder="备注"
                      style="width: 285px"
                    />
                  </a-form-item>

                  <a-form-item label="城市" name="city">
                    <a-select
                      v-model:value="formState.city"
                      placeholder="请选择"
                      allowClear
                      style="width: 285px"
                    >
                      <a-select-option v-for="(item, index) in cityList" :key="index" :value="item">
                        {{ item }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item label="粉丝ID" name="fansId">
                    <a-input v-model:value="formState.fansId" placeholder="粉丝ID" />
                  </a-form-item>

                  <!-- <a-form-item label="粉丝ID" name="wxid">
                    <a-input v-model:value="formState.wxid" placeholder="粉丝ID" />
                  </a-form-item> -->

                  <a-form-item style="text-align: right">
                    <a-button type="primary" @click="search">搜索</a-button>
                    <a-button @click="reset" style="margin-left: 10px">重置</a-button>
                  </a-form-item>
                </div>
              </SearchDrawer>
            </a-form>

            <a-button type="primary" @click="search">搜索</a-button>
            <a-button @click="reset">重置</a-button>
            <a-button type="primary" @click="advancedSearch">高级搜索</a-button>
          </div>

          <a-alert
            description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
            type="info"
            banner
            style="margin-bottom: 10px; padding: 10px"
          />

          <a-table
            style="overflow-x: scroll"
            :columns="columns"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            @change="changePage"
            rowKey="id"
            size="small"
            :scroll="{ x: 100 }"
          >
            <template #emptyText>
              <a-empty description="暂无数据" />
            </template>

            <template #headerCell="{ column }">
              <template v-if="column.key === 'id'">
                <span>粉丝id</span>
              </template>

              <template v-else-if="column.key === 'avatar'">
                <div style="text-align: center">
                  <span>头像</span>
                </div>
              </template>
            </template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'account'">
                <a-popover>
                  <template #content>
                    <div style="width: 600px; overflow-x: scroll">
                      {{ record.account }}
                    </div>
                  </template>
                  <div class="hiddenText">{{ record.account }}</div>
                </a-popover>
              </template>

              <template v-else-if="column.key === 'avatar'">
                <div class="imgBox">
                  <img :src="record.avatar" alt="" />
                </div>
              </template>

              <template v-else-if="column.key === 'createTime'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="备注">
                    <div style="display: flex; align-items: center">
                      <a-tooltip placement="top" v-if="!record.isRemarkShow">
                        <template #title>
                          <span>{{ record.remark }}</span>
                        </template>
                        <span class="hiddenText">{{ record.remark }}</span>
                      </a-tooltip>
                      <a-input
                        v-else
                        v-model:value="record.remark"
                        @blur="editRemark(record.id, record.remark)"
                        style="border: 0"
                      />
                      <EditOutlined
                        @click="EditRemarkSet(record)"
                        v-if="!record.isRemarkShow"
                        style="margin-left: 6px; color: #1890ff"
                      />
                    </div>
                  </a-descriptions-item>
                  <a-descriptions-item label="创建时间">
                    {{ timeFormat(record.createTime) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="更新时间">
                    {{ timeFormat(record.updateTime) }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'nickName'">
                <a-descriptions bordered size="small" :column="1">
                  <a-descriptions-item label="昵称" :labelStyle="{ width: '70px' }">
                    <a-tooltip placement="top">
                      <template #title>
                        <span>{{ record.nickName }}</span>
                      </template>
                      <span class="hiddenText">{{ record.nickName }}</span>
                      <a @click="copyToCliboard(record.nickName)"><CopyOutlined /></a>
                    </a-tooltip>
                  </a-descriptions-item>
                  <a-descriptions-item label="性别">
                    <a-tag color="blue" v-if="record.sex == '1'">男</a-tag>
                    <a-tag color="pink" v-else-if="record.sex == '2'">女</a-tag>
                    <a-tag color="red" v-else>未知</a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="余额">
                    <a @click="editBalance(record)">
                      {{ (record.balance / 100).toFixed(2) }}
                      <EditOutlined />
                    </a>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'wxid'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '80px' }">
                  <a-descriptions-item label="微信号">{{ record.account }}</a-descriptions-item>
                  <a-descriptions-item label="微信id">
                    {{ record.wxid }}
                    <a @click="copyToCliboard(record.wxid)"><CopyOutlined /></a>
                  </a-descriptions-item>
                  <a-descriptions-item label="城市">
                    {{ record.city }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'wechatId'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="粉丝id">
                    {{ record.id }}
                    <a @click="copyToCliboard(record.id)"><CopyOutlined /></a>
                  </a-descriptions-item>
                  <a-descriptions-item label="平台id">{{ record.robotId }}</a-descriptions-item>
                  <a-descriptions-item label="平台wxid">
                    {{ record.wechatId }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>
            </template>
          </a-table>

          <EditRemark ref="editRemarkRef" @refresh="getList"></EditRemark>
          <EditBalance ref="EditBalanceRef" @refresh="getList"></EditBalance>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;
  margin: 0 auto;
  border-radius: 50%;
  overflow: hidden;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 300px;
  img {
    width: 100%;
  }
}

.robitStatusClass {
  text-align: center;
}
</style>
